package com.zj.core.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import android.widget.LinearLayout
import com.customcamera.widget.CameraManager
import com.customcamera.widget.ISavePicCallback
import com.zj.core.R
import com.zj.core.base.TitleBarActivity
import android.os.Bundle
import com.fileutils.ImageFileUtil
import android.app.Activity
import android.os.Build
import com.zj.core.ui.CameraActivityUi
import com.zj.core.tools.Constant.Companion.PICTURE_RES_KEY
import com.zj.core.tools.Constant.Companion.REQUEST_PICTURE_KEY
import org.jetbrains.anko.setContentView


class CameraActivity: TitleBarActivity(),View.OnClickListener, ISavePicCallback {
    private var mCameraManager: CameraManager? = null
    private val flashHint = arrayOf("关闭", "看不清？打开灯光")
    private val REQUEST_PICTURE = 2
    private var selectIntent:Intent?=null
    lateinit var view: CameraActivityUi

    companion object {
        @SuppressLint("StaticFieldLeak")
        var CameraActivity:Activity?=null
    }

    override fun onCreate(groupView: LinearLayout): View?{
        view= CameraActivityUi(groupView)
        return view.setContentView(this)
    }

    override fun initView(){
        CameraActivity =this

        selectIntent = Intent(Intent.ACTION_PICK)

        setTitleBarVisible(View.GONE)
        mCameraManager = CameraManager.getInstance(this)
        mCameraManager?.bindOptionMenuView(view.camera_tv_light,null, flashHint, null)

        with(view){
            this.camera_container.bindActivity(this@CameraActivity)
            this.camera_tv_light.setOnClickListener(this@CameraActivity)
            this.camera_iv_take.setOnClickListener(this@CameraActivity)
            this.camera_iv_picture.setOnClickListener(this@CameraActivity)
            this.camera_iv_back.setOnClickListener(this@CameraActivity)
        }
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when(v?.id){
            R.id.camera_tv_light->{                     //闪光灯
                view.camera_container.switchFlashMode()
            }

            R.id.camera_iv_take->{                              //拍照
                view.camera_container.takePicture(this)
            }

            R.id.camera_iv_picture->{                    //相册
                selectIntent?.type = "image/*"
                startActivityForResult(selectIntent, REQUEST_PICTURE)
            }

            R.id.camera_iv_back->{                         //退出
                finish()
            }
        }
    }

    /**
     * 相册返回
     *
     * @param req
     * @param res
     * @param data
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode==Activity.RESULT_OK) {
            try {
                val uri = data?.data
                //                File file = new FileStorage().createIconFile(); //工具类
                if (Build.VERSION.SDK_INT >= 24) {
                    //                    // 针对Android7.0，需要通过FileProvider封装过的路径，提供给外部调用
                    //                    // 通过FileProvider创建一个content类型的Uri，进行封装
                    //                    Uri imageUri = FileProvider.getUriForFile(activity, "com.pecoo.ifcoo.fileprovider", file);
                    //                    output = file;
                } else {
                    // 7.0以下，如果直接拿到相机返回的intent值，拿到的则是拍照的原图大小，很容易发生OOM，所以我们同样将返回的地址，保存到指定路径，返回到Activity时，去指定路径获取，压缩图片
                    //                    output = ImageUtils.createFile(FileUtils.getInst().getPhotoPathForLockWallPaper(), true);
                    //                    Uri imageUri = Uri.fromFile(output);
                }
                if (uri != null) {
                    jumpToPicture(ImageFileUtil.CustomClass().setUriName(uri).setTakePhoto(false))
                    //ToastUtil.showShort(getContext(), UriUtils.getPath(getContext(), uri));
                    //Log.d("url", UriUtils.getPath(getContext(), uri));
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {}
    }

    /**
     * 拍照结果返回,释放相机
     *
     * @param picPath
     */
    override fun saveComplete(picPath: String?){
        jumpToPicture(ImageFileUtil.CustomClass().setStringName(picPath).setTakePhoto(true))
        destoryCamera()
    }

    /**
     * 跳到照片展示页面
     */
    private fun jumpToPicture(myClass:ImageFileUtil.CustomClass?){
        Bundle().let {
            it.putSerializable(PICTURE_RES_KEY,myClass)
            activityJumpForResult(this,REQUEST_PICTURE_KEY, PictureActivity().javaClass,it)
        }
    }

    override fun saveFailure(msg: String?) {}

    public override fun onResume() {
        super.onResume()
        view.camera_container.onStart()
    }

    public override fun onPause() {
        super.onPause()
        view.camera_container.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        destoryCamera()
        if(CameraActivity !=null){
            CameraActivity =null
        }
    }

    /**
     * 释放相机
     */
    private fun destoryCamera(){
        if(mCameraManager!=null){
            mCameraManager?.unbindView()
            mCameraManager=null
        }
        view.camera_container.releaseCamera()
    }
}